<template>
  <div class="class-schedule">
    <div class="schedule-header">
      <h3 class="section-title">
        <el-icon><Clock /></el-icon>
        课程表
      </h3>
      <div v-if="isAdminLoggedIn" class="header-actions">
        <el-button
          type="primary"
          size="small"
          @click="openEditDialog"
        >
          <el-icon><Edit /></el-icon>
          编辑课程表
        </el-button>
      </div>
    </div>

    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="8" animated />
    </div>

    <div v-else-if="scheduleData.length === 0" class="no-schedule">
      <el-empty description="暂无课程安排">
        <el-button
          v-if="isAdminLoggedIn"
          type="primary"
          @click="openEditDialog"
        >
          添加课程表
        </el-button>
      </el-empty>
    </div>

    <div v-else class="schedule-table">
      <table class="schedule-table-content">
        <thead>
          <tr>
            <th class="time-header">时间</th>
            <th class="day-header">周一</th>
            <th class="day-header">周二</th>
            <th class="day-header">周三</th>
            <th class="day-header">周四</th>
            <th class="day-header">周五</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="session in sessions" :key="session.order">
            <td class="time-cell">
              <div class="time-range">
                <div class="start-time">{{ session.startTime }}</div>
                <div class="separator">-</div>
                <div class="end-time">{{ session.endTime }}</div>
              </div>
            </td>
            <td
              v-for="day in [1, 2, 3, 4, 5]"
              :key="day"
              class="subject-cell"
            >
              <div
                v-if="getScheduleByDayAndSession(day, session.order)"
                class="subject-item"
                :style="getSubjectStyle(getScheduleByDayAndSession(day, session.order).subject)"
              >
                <div class="subject-name">
                  {{ getScheduleByDayAndSession(day, session.order).subject }}
                </div>
                <div class="subject-details">
                  <span v-if="getScheduleByDayAndSession(day, session.order).teacherName" class="teacher">
                    {{ getScheduleByDayAndSession(day, session.order).teacherName }}
                  </span>
                  <span v-if="getScheduleByDayAndSession(day, session.order).classroom" class="classroom">
                    {{ getScheduleByDayAndSession(day, session.order).classroom }}
                  </span>
                </div>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="showEditDialog"
      title="编辑课程表"
      width="900px"
      @close="resetEditForm"
    >
      <div class="edit-form">
        <el-alert
          title="编辑说明"
          type="info"
          :closable="false"
          style="margin-bottom: 20px"
        >
          <template #default>
            <div>
              • 支持编辑时间段、科目、教师和教室信息<br>
              • 请确保时间安排合理，避免冲突<br>
              • 留空表示该时间段无课程<br>
              • 修改时间段会影响所有天的对应节次
            </div>
          </template>
        </el-alert>

        <table class="edit-table">
          <thead>
            <tr>
              <th>时间</th>
              <th>周一</th>
              <th>周二</th>
              <th>周三</th>
              <th>周四</th>
              <th>周五</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="session in sessions" :key="session.order">
              <td class="time-cell">
                <div class="time-edit">
                  <el-time-picker
                    v-model="editTimeData[session.order].startTime"
                    format="HH:mm"
                    value-format="HH:mm"
                    placeholder="开始时间"
                    size="small"
                    style="width: 100%"
                    @change="updateSessionTime(session.order, 'start', $event)"
                  />
                  <div class="time-separator">-</div>
                  <el-time-picker
                    v-model="editTimeData[session.order].endTime"
                    format="HH:mm"
                    value-format="HH:mm"
                    placeholder="结束时间"
                    size="small"
                    style="width: 100%"
                    @change="updateSessionTime(session.order, 'end', $event)"
                  />
                </div>
              </td>
              <td v-for="day in [1, 2, 3, 4, 5]" :key="`${day}-${session.order}`">
                <el-input
                  v-model="editFormData[`${day}-${session.order}`].subject"
                  placeholder="科目"
                  size="small"
                />
                <el-input
                  v-model="editFormData[`${day}-${session.order}`].teacherName"
                  placeholder="教师"
                  size="small"
                  style="margin-top: 4px"
                />
                <el-input
                  v-model="editFormData[`${day}-${session.order}`].classroom"
                  placeholder="教室"
                  size="small"
                  style="margin-top: 4px"
                />
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEditDialog = false">取消</el-button>
          <el-button type="primary" @click="handleSaveSchedule" :loading="saving">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Clock, Edit } from '@element-plus/icons-vue'
import { scheduleApi } from '@/api/schedule'

const props = defineProps({
  studentId: {
    type: Number,
    required: true
  },
  isAdminLoggedIn: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['refresh'])

const loading = ref(false)
const saving = ref(false)
const showEditDialog = ref(false)
const scheduleData = ref([])

// 课程时间段
const sessions = ref([
  { order: 1, startTime: '8:00', endTime: '8:40' },
  { order: 2, startTime: '8:50', endTime: '9:30' },
  { order: 3, startTime: '10:00', endTime: '10:40' },
  { order: 4, startTime: '10:50', endTime: '11:30' },
  { order: 5, startTime: '14:00', endTime: '14:40' },
  { order: 6, startTime: '14:50', endTime: '15:30' },
  { order: 7, startTime: '15:50', endTime: '16:30' },
  { order: 8, startTime: '16:40', endTime: '17:20' }
])

// 编辑表单数据
const editFormData = ref({})

// 时间编辑数据
const editTimeData = ref({})

// 科目颜色映射
const subjectColors = {
  '语文': '#FF6B6B',
  '数学': '#4ECDC4',
  '英语': '#45B7D1',
  '科学': '#96CEB4',
  '音乐': '#FECA57',
  '美术': '#DDA0DD',
  '体育': '#FFA07A',
  '品德': '#98D8C8',
  '信息技术': '#B19CD9',
  '其他': '#95A5A6'
}

// 根据星期几和节次获取课程
const getScheduleByDayAndSession = (day, sessionOrder) => {
  return scheduleData.value.find(item =>
    item.dayOfWeek === day && item.sessionOrder === sessionOrder
  )
}

// 获取科目颜色
const getSubjectStyle = (subject) => {
  const color = subjectColors[subject] || subjectColors['其他']
  return {
    backgroundColor: color,
    color: 'white'
  }
}

// 加载课程表数据
const loadScheduleData = async () => {
  if (!props.studentId) {
    return
  }

  try {
    loading.value = true
    const response = await scheduleApi.getClassSchedule(props.studentId)
    scheduleData.value = response.data || []
  } catch (error) {
    console.error('加载课程表失败:', error)
    ElMessage.error('加载课程表失败')
    scheduleData.value = []
  } finally {
    loading.value = false
  }
}

// 打开编辑对话框
const openEditDialog = () => {
  if (!props.isAdminLoggedIn) {
    ElMessage.warning('请先登录管理员账号')
    return
  }

  initializeEditForm()
  showEditDialog.value = true
}

// 初始化编辑表单
const initializeEditForm = () => {
  const formData = {}
  const timeData = {}

  for (const session of sessions.value) {
    // 初始化时间编辑数据
    timeData[session.order] = {
      startTime: session.startTime,
      endTime: session.endTime
    }

    for (const day of [1, 2, 3, 4, 5]) {
      const key = `${day}-${session.order}`
      const existingSchedule = getScheduleByDayAndSession(day, session.order)

      formData[key] = {
        dayOfWeek: day,
        sessionOrder: session.order,
        startTime: session.startTime,
        endTime: session.endTime,
        subject: existingSchedule?.subject || '',
        teacherName: existingSchedule?.teacherName || '',
        classroom: existingSchedule?.classroom || '',
        isActive: true
      }
    }
  }

  editFormData.value = formData
  editTimeData.value = timeData
}

// 重置编辑表单
const resetEditForm = () => {
  editFormData.value = {}
  editTimeData.value = {}
}

// 更新时间段
const updateSessionTime = (sessionOrder, type, time) => {
  if (!time) return

  // 更新时间段数据
  if (type === 'start') {
    editTimeData.value[sessionOrder].startTime = time
  } else {
    editTimeData.value[sessionOrder].endTime = time
  }

  // 更新所有天的对应节次时间
  for (const day of [1, 2, 3, 4, 5]) {
    const key = `${day}-${sessionOrder}`
    if (editFormData.value[key]) {
      if (type === 'start') {
        editFormData.value[key].startTime = time
      } else {
        editFormData.value[key].endTime = time
      }
    }
  }

  // 更新sessions中的时间
  const session = sessions.value.find(s => s.order === sessionOrder)
  if (session) {
    if (type === 'start') {
      session.startTime = time
    } else {
      session.endTime = time
    }
  }
}

// 保存课程表
const handleSaveSchedule = async () => {
  try {
    saving.value = true

    // 验证时间段设置
    for (const session of sessions.value) {
      const startTime = editTimeData.value[session.order]?.startTime
      const endTime = editTimeData.value[session.order]?.endTime

      if (!startTime || !endTime) {
        ElMessage.error(`第${session.order}节课的时间设置不完整`)
        return
      }

      if (startTime >= endTime) {
        ElMessage.error(`第${session.order}节课的开始时间必须早于结束时间`)
        return
      }
    }

    const scheduleList = Object.values(editFormData.value).filter(item =>
      item.subject.trim() !== ''
    )

    if (scheduleList.length === 0) {
      ElMessage.warning('请至少添加一门课程')
      return
    }

    await scheduleApi.batchUpdateSchedule({
      studentId: props.studentId,
      scheduleList: scheduleList
    })

    ElMessage.success('课程表保存成功')
    showEditDialog.value = false
    loadScheduleData()
  } catch (error) {
    console.error('保存课程表失败:', error)
    ElMessage.error('保存课程表失败')
  } finally {
    saving.value = false
  }
}

// 刷新数据
const refresh = () => {
  loadScheduleData()
}

// 暴露刷新方法给父组件
defineExpose({
  refresh
})

// 监听学生ID变化
watch(() => props.studentId, () => {
  if (props.studentId) {
    loadScheduleData()
  }
}, { immediate: true })
</script>

<style scoped>
.class-schedule {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  height: 100%;
}

.schedule-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 8px;
}

.loading-container {
  padding: 40px;
}

.no-schedule {
  text-align: center;
  padding: 40px;
}

.schedule-table {
  overflow-x: auto;
}

.schedule-table-content {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
}

.schedule-table-content th,
.schedule-table-content td {
  border: 1px solid #e4e7ed;
  padding: 8px;
  text-align: center;
}

.time-header,
.day-header {
  background-color: #f5f7fa;
  font-weight: bold;
  color: #606266;
  min-width: 100px;
}

.time-cell {
  background-color: #fafafa;
  font-weight: 500;
  min-width: 140px;
  padding: 8px;
}

.time-range {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  white-space: nowrap;
}

.start-time,
.end-time {
  font-size: 12px;
  color: #606266;
}

.separator {
  color: #999;
  font-size: 12px;
  margin: 0 2px;
}

.subject-cell {
  padding: 4px;
  min-width: 120px;
}

.subject-item {
  padding: 8px 4px;
  border-radius: 4px;
  min-height: 60px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  transition: all 0.3s ease;
}

.subject-item:hover {
  transform: scale(1.02);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.subject-name {
  font-weight: bold;
  font-size: 13px;
  margin-bottom: 2px;
}

.subject-details {
  font-size: 10px;
  opacity: 0.9;
  display: flex;
  flex-direction: column;
  gap: 1px;
}

.teacher,
.classroom {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.edit-form {
  max-height: 500px;
  overflow-y: auto;
}

.edit-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 13px;
}

.edit-table th,
.edit-table td {
  border: 1px solid #e4e7ed;
  padding: 8px;
  text-align: center;
}

.edit-table th {
  background-color: #f5f7fa;
  font-weight: bold;
}

.time-label {
  font-weight: 500;
  color: #606266;
  white-space: nowrap;
}

.time-edit {
  display: flex;
  flex-direction: column;
  gap: 4px;
  align-items: center;
  min-width: 120px;
}

.time-separator {
  color: #999;
  font-size: 12px;
  font-weight: bold;
  margin: 2px 0;
}

@media (max-width: 768px) {
  .schedule-table-content {
    font-size: 12px;
  }

  .time-header,
  .day-header {
    min-width: 80px;
    padding: 4px;
  }

  .time-cell {
    min-width: 100px;
    padding: 4px;
  }

  .subject-cell {
    min-width: 60px;
    padding: 2px;
  }

  .subject-name {
    font-size: 11px;
  }

  .subject-details {
    font-size: 9px;
  }

  .time-range {
    font-size: 10px;
  }

  .start-time,
  .end-time {
    font-size: 10px;
  }

  .separator {
    font-size: 10px;
  }
}
</style>